//
//  YXUDCaching.swift
//  
//
//  Created by tangbl93 on 2021/2/27.
//

import Foundation

// MARK: YXUDCaching
public final class YXUDCaching: NSObject {
    
    // shared cache
    public static var shared: YXUDCaching = YXUDCaching()
    
    // UserDefaults as backend service
    fileprivate var userDefaults: UserDefaults
    
    init(userDefaults: UserDefaults = UserDefaults.standard) {
        self.userDefaults = userDefaults
    }
}

extension YXUDCaching: YXCaching {
    
    public override func value(forKey key: String) -> Any? {
        return userDefaults.value(forKey: key)
    }
    
    public func value(forKey key: String, default object: Any) -> Any {
        return userDefaults.value(forKey: key) ?? object
    }
    
    public func set(_ value: Any?, forKey key: String) {
        userDefaults.setValue(value, forKey: key)
    }
    
    public func transition(from oldKey: String, to newKey: String) {
        guard let value = value(forKey: oldKey) else { return }
        
        removeObject(forKey: oldKey)
        set(value, forKey: newKey)
    }
    
    public func removeAll() {
        userDefaults.dictionaryRepresentation().keys.forEach(removeObject)
    }
    
    public func removeObject(forKey key: String) {
        userDefaults.removeObject(forKey: key)
    }
}
